import { defineStore } from 'pinia'
import { login, getInfo, logout } from '@/apis/login'
import { setCookie, getCookie, removeCookie } from '@/utils/auth'
import { LoginBody } from "@/views/login.vue"

export interface UserState {
    token: string,
    user: {},
    roles: Array<string>,
    permissions: Array<string>,
}

export const useStore = defineStore(
    {
        id: 'userStore',
        state: () => ({
            token: getCookie(),
            user: {},
            //角色
            roles: [],
            //权限
            permissions: [],
        }),
        getters: {
        },
        actions: {
            Login(loginBody: LoginBody) {
                return new Promise((resolve, reject) => {
                    login(loginBody).then((response) => {
                        console.log("🚀 ~ file: user.ts ~ line 30 ~ login ~ response", response)
                        const { tokenValue } = response.data
                        setCookie(tokenValue)
                        this.token = tokenValue
                        resolve(tokenValue);
                    }).catch((error) => {
                        reject(error);
                    });
                });
            },

            //获得用户信息
            GetInfo() {
                return new Promise((resolve, reject) => {
                    getInfo().then(response => {
                        const { user, roles, permissions } = response.data
                        this.user = user
                        this.roles = roles
                        this.permissions = permissions
                        resolve(response)
                    }).catch((error) => {
                        reject(error)
                    })
                })
            },


            //登出
            Logout() {
                return new Promise((resolve, reject) => {
                    logout().then((response) => {
                        removeCookie()
                        this.token = ''
                        resolve(response);
                    }).catch((error) => {
                        reject(error);
                    });
                });
            }
        }
    }
)

